<template>
  <t-form
    ref="form"
    :class="['item-container', `register-${type}`]"
    :data="formData"
    :rules="FORM_RULES"
    label-width="0"
    @submit="onSubmit"
  >

    <t-form-item name="username">
      <t-input v-model="formData.username" type="text" size="large" placeholder="请输入用户名">
        <template #prefix-icon>
          <t-icon name="user" />
        </template>
      </t-input>
    </t-form-item>

    <t-form-item name="email">
        <t-input v-model="formData.email" type="text" size="large" placeholder="请输入您的邮箱">
          <template #prefix-icon>
            <t-icon name="mail" />
          </template>
        </t-input>
      </t-form-item>

    <t-form-item name="password">
      <t-input
        v-model="formData.password"
        size="large"
        :type="showPsw ? 'text' : 'password'"
        clearable
        placeholder="请输入登录密码"
      >
        <template #prefix-icon>
          <t-icon name="lock-on" />
        </template>
        <template #suffix-icon>
          <t-icon :name="showPsw ? 'browse' : 'browse-off'" @click="showPsw = !showPsw" />
        </template>
      </t-input>
    </t-form-item>

    

    <t-form-item class="check-container" name="checked">
      <t-checkbox v-model="formData.checked">我已阅读并同意 </t-checkbox>
      <span class="link" @click="showAgreementDrawer = true">MyAdmin服务协议</span> 和
      <span class="link" @click="showPrivacyDrawer = true">MyAdmin 隐私声明</span>
    </t-form-item>

    <t-form-item>
      <t-button block size="large" type="submit"> 注册 </t-button>
    </t-form-item>


  </t-form>
  <Drawer
    v-model:visible="showAgreementDrawer"
    header="MyAdmin 服务协议"
    size="medium"
    placement="right"
    confirmBtn="我已知晓"
    cancelBtn="取消"
  >
    <div style="padding: 16px; max-height: 70vh; overflow-y: auto;">
      省略一万字的MyAdmin服务协议的内容
    </div>
  </Drawer>
  <Drawer
    v-model:visible="showPrivacyDrawer"
    header="MyAdmin 隐私声明"
    size="medium"
    placement="right"
    confirmBtn="我已知晓"
    cancelBtn="取消"
  >
    <div style="padding: 16px; max-height: 70vh; overflow-y: auto;">
      省略一万字的MyAdmin隐私声明的内容
    </div>
  </Drawer>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { MessagePlugin, FormRule, DialogPlugin, Drawer } from 'tdesign-vue-next';
import { register } from '@/api/user/index';
import type { UserRegisterParam } from '@/api/user/types';

/**
 * 注册表单初始数据
 */
const INITIAL_DATA: UserRegisterParam & { checked: boolean } = {
  username: '',
  password: '',
  email: '',
  checked: false,
};

/**
 * 用户名校验规则：4-20位，只能包含字母、数字、下划线
 */
const usernamePattern = /^[a-zA-Z0-9_]{4,20}$/;
/**
 * 密码校验规则：8-32位，必须包含字母和数字
 */
const passwordPattern = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]{8,32}$/;

/**
 * 注册表单校验规则
 */
const FORM_RULES: Record<string, FormRule[]> = {
  username: [
    { required: true, message: '用户名必填', type: 'error' },
    { validator: val => usernamePattern.test(val), message: '用户名4-20位，只能包含字母、数字、下划线', type: 'error' }
  ],
  email: [
    { required: true, message: '邮箱必填', type: 'error' },
    { email: true, message: '请输入正确的邮箱', type: 'warning' },
  ],
  password: [
    { required: true, message: '密码必填', type: 'error' },
    { validator: val => passwordPattern.test(val), message: '密码8-32位，必须包含字母和数字', type: 'error' }
  ],
  verifyCode: [{ required: true, message: '验证码必填', type: 'error' }],
};

/**
 * 当前表单类型（暂未用到，可扩展）
 */
const type = ref('email');

/**
 * 注册表单ref
 */
const form = ref();
/**
 * 注册表单数据
 */
const formData = ref({ ...INITIAL_DATA });

/**
 * 是否显示密码明文
 */
const showPsw = ref(false);

/**
 * 控制服务协议/隐私声明抽屉显示
 */
const showAgreementDrawer = ref(false);
const showPrivacyDrawer = ref(false);

/**
 * 注册成功事件
 */
const emit = defineEmits(['registerSuccess']);

/**
 * 注册表单提交
 * @param validateResult 校验结果
 */
const onSubmit = async ({ validateResult }: { validateResult: boolean }) => {
  if (validateResult === true) {
    if (!formData.value.checked) {
      MessagePlugin.error('请同意MyAdmin服务协议和MyAdmin 隐私声明');
      return;
    }
    try {
      const { checked, ...params } = formData.value;
      // 日志：打印注册参数
      console.log('[注册请求参数]', params);
      const res = await register(params);
      // 日志：打印注册响应
      console.log('[注册响应]', res.data);
      if (res.data && res.data.code === 200) {
        MessagePlugin.success('注册成功');
        emit('registerSuccess');
      } else {
        MessagePlugin.error(res.data?.message || '注册失败');
      }
    } catch (error) {
      MessagePlugin.error('注册异常，请稍后重试');
      // 日志：打印异常信息
      console.error('[注册失败]', error);
    }
  }
};

</script>

<style lang="less" scoped>
@import url('../login.less');
</style>